/**
 * 2018年3月1日, 下午2:24:56
 * @Author Yunlong,Ti
 * 
 */

package com.autonavi.yunda.yunji.common.thread;

import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class AmapThreadContext {

  private static final ThreadLocal<Map<String, Object>> contextMap = new ThreadLocal<Map<String, Object>>();

  public static void put(String key, Object value) {
    if (contextMap.get() == null) {
      contextMap.set(new HashMap<>());
    }
    contextMap.get().put(key, value);
  }

  public static Object get(String key) {
    if (contextMap.get() == null) {
      contextMap.set(new HashMap<>());
    }
    return contextMap.get().get(key);
  }

  public static Map<String, Object> getContextMapCopy() {
    if (contextMap.get() == null) {
      contextMap.set(new HashMap<>());
    }
    return Collections.unmodifiableMap(new HashMap<>(contextMap.get()));
  }

  public static void initialThreadContext(Map<String, Object> initialMap, Map<String, String> mdcContextMap) {
    clearContext();
    Map<String, Object> map = new HashMap<>(initialMap);
    contextMap.set(map);
    MDC.setContextMap(mdcContextMap);
  }

  public static void clearContext() {
    if (contextMap.get() == null) {
      contextMap.set(new HashMap<>());
    } else {
      contextMap.get().clear();
    }
    MDC.clear();
  }

  public static void addKeyIfExist(String key, HttpServletRequest request) {
    String value = request.getParameter(key);
    if (value != null) {
      put(key, value);
    }
  }

}
